package com.example.administrator.netdemo.network;

import android.content.Context;
import android.util.Log;

import com.cyw.baselibrary.utils.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.observers.ResourceObserver;

/**
 * Created by luquan on 2017/2/13.
 */

public class SimpleSubscriber<T> extends ResourceObserver<T> {

    private Context context;
    private CommonNextCallBack<T> commonCallBack;
    private boolean showTips = true;

    public SimpleSubscriber<T> setShowTips(boolean showTips) {
        this.showTips = showTips;
        return this;
    }

    public SimpleSubscriber(CommonNextCallBack<T> commonCallBack, Context context) {
        this.commonCallBack = commonCallBack;
        this.context = context;
    }



    /**
     * 对错误进行统一处理
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        try {
            printError(e);
            if (showTips) {
                if (e instanceof SocketTimeoutException) {
                    ToastUtils.showShort(context,"连接超时，请稍后再试");
//                    T.showShort("");
                } else if (e instanceof ConnectException || e instanceof UnknownHostException) {
                    ToastUtils.showShort(context,"网络错误，请检查您的网络状态");
                } else {
                    ToastUtils.showShort(context,"请求失败");
                }
            }
            if (commonCallBack != null) {
                commonCallBack.onNext(ApiException.NETWORK_ERR, null);
            }
        } catch (Exception e1) {
            printError(e1);
        }

    }

    @Override
    public void onComplete() {

    }

    /**
     * 打印错误信息
     *
     * @param e
     */
    private void printError(Throwable e) {
        if (e != null && e.getStackTrace().length > 0) {
            StackTraceElement[] elements = e.getStackTrace();
            StringBuilder sb = new StringBuilder();
            sb.append(e.toString());
            sb.append("\n");
            for (StackTraceElement element : elements) {
                sb.append(element.toString());
                sb.append("\n");
            }
            Log.e("cyw", "" + sb.toString());
        } else {
            Log.e("cyw", "" + e.toString());
        }
    }


    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param t 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T t) {
        if (commonCallBack != null) {
            commonCallBack.onNext(ApiException.REQUEST_SUCCESS, t);
        }
    }

}
